package com.googlecode.lohr.utils;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DataUtils {

	public static final BigDecimal ZERO= new BigDecimal("0.00");
	
	public static final DateFormat[] SUPPORTED_DATE_FORMATS= {
		new SimpleDateFormat("yyyy-MM-dd"),
		new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
		new SimpleDateFormat("MM/dd/yyyy"),
		new SimpleDateFormat("MMM d yyyy hh:mma"),
		new SimpleDateFormat("yyyyMMdd")
	};

	public static BigDecimal toSafeBigDecimal(Object object) {
		if (object == null) {
			return ZERO;
		}
		if (object instanceof Number) {
			return new BigDecimal(((Number)object).toString());
		}

		String s= object.toString();
		for (int i= s.length(); 0 < i--;) {
			char c= s.charAt(i);
			if (Character.isDigit(c) == false) {
				if (c != '.') {
					if (i == s.length() - 1) {
						s= s.substring(0, i);
					}
					else
						s= s.substring(0, i)+s.substring(i+1);
				}
			}
		}
		try {
			return new BigDecimal(s);
		}
		catch (Throwable t) {			
		}
		return ZERO;
	}

	public static String toSafeString(Object object) {
		if (object == null) {
			return "";
		}
		if (object instanceof String) {
			if (object.equals("null")) {
				return "";
			}
			return (String)object;
		}
		return object.toString();
	}

	public static Date toSafeDate(Object o1) {
		Date date= toDate(o1);
		if (date != null)
			return date;
		return new Date();
	}

	/**
	 * @return null if the given value cannot be converted to a date
	 */
	public static Date toDate(Object o1) {
		if (o1 == null)
			return null;
		if (o1 instanceof Date)
			return (Date)o1;
		if (o1 instanceof java.sql.Date) 
			return new Date(((java.sql.Date)o1).getTime());
		if (o1 instanceof Calendar) 
			return ((Calendar)o1).getTime();

		String s= o1.toString();
		for (int i= 0; i < SUPPORTED_DATE_FORMATS.length; i++) {
			try {
				return SUPPORTED_DATE_FORMATS[i].parse(s);
			}
			catch (Throwable t) {
			}
		}

		return null;
	}

	public static Double toSafeDouble(Object object) {
		BigDecimal bigDecimal= toSafeBigDecimal(object);
		return new Double(bigDecimal.doubleValue());
	}

	public static String toFormattedNumber(Object aNumber, NumberFormat numberFormat) {
		BigDecimal bigDecimal= toSafeBigDecimal(aNumber);
		String out= null;
		try {
			out = numberFormat.format(bigDecimal);
			if (out.compareToIgnoreCase("0.00") == 0)
				out = "";
		} catch (Exception e) {
			out ="";
		}
		return out;
	}

}
